package com.situ.mall.admin.controller;

import com.situ.mall.common.entity.Category;
import com.situ.mall.common.entity.Product;
import com.situ.mall.common.service.IAttachmentService;
import com.situ.mall.common.service.ICategoryService;
import com.situ.mall.common.service.IProductService;
import com.situ.mall.common.vo.EditProductVO;
import com.situ.mall.common.vo.TableVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yangkx
 * @create 2023-09-12-14:12
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private ICategoryService categoryService;

    //打开商品管理页面
    @GetMapping("/page")
    public String page(){
        return "product";
    }

    //查询商品表格
    @GetMapping("/table")
    @ResponseBody
    public TableVO table(Integer page, Integer limit, Integer categoryId, String name, String edition){
        return productService.table(page,limit,categoryId,name,edition);
    }

    //保存
    @PostMapping("/save")
    @ResponseBody
    public void save(Product p){
        productService.saveProduct(p);
    }

    //删除
    @PostMapping("/delete/{productId}")
    @ResponseBody
    public void delete(@PathVariable("productId")Integer id){
        productService.delete(id);
    }

    //编辑——根据ID查询该行数据带到前台
    @GetMapping("/selectById/{id}")
    @ResponseBody
    public EditProductVO selectById(@PathVariable("id")Integer id) {
        return productService.selectById(id);
    }

    //查询二级分类
    @GetMapping("/all")
    @ResponseBody
    public List<Category> all(){
        return productService.all();
    }

    //切换按钮——切换上架状态
    @PostMapping("/status")
    @ResponseBody
    public void status(Integer id,String status){
        Product p = new Product();
        p.setId(id);
        p.setStatus(status);
        //有值的更新，没有值的不更新
        productService.updateById(p);

        //如果是下架切换到上架，则把所属分类的状态也切换到上架
        if (status.equals("0")){
            EditProductVO product = productService.selectById(id);
            Category category = new Category();
            category.setId(product.getCategoryId());
            category.setStatus("0");
            categoryService.updateById(category);
        }
    }

    //把商品的id保存到对应的附件表里
    @PostMapping("/bind")
    @ResponseBody
    public void bind(Integer id,String attIds){
        //需要更新的附件ID，需要给对应附件插入的商品id，需要给对应附件插入的源（表名）
        attachmentService.bind(attIds,id,"product");
    }


}
